const https = require('https')
const http = require('http')

const RestClient = {
    http(host, port, url, method, headers, data, callback, failCallback, timeout) {
        this.request(host, port, url, method, headers, data, callback, failCallback, timeout, true)
    },
    https(host, port, url, method, headers, data, callback, failCallback, timeout) {
        this.request(host, port, url, method, headers, data, callback, failCallback, timeout)
    },
    request(host, port, url, method, headers, data, callback, failCallback, timeout, useHttp) {
        timeout = timeout || 30000
        let options = {
            hostname: host,
            port: port,
            path: url,
            method: method,
            headers: headers,
            timeout: timeout
        }

        console.log('request options: ', options)
        console.log('request data: ', data)

        let fn = https;
        if (useHttp) {
            fn = http;
        }

        let req = fn.request(options, (res) => {
            let resposeData = '';
            res.on('data', chunk => {
                resposeData += chunk.toString()
            })

            res.on('end', ()=> {
                console.log('response: ', res)
                console.log('response data: ', resposeData)
                if (res.statusCode > 299 || res.statusCode < 200) {
                    let message = res.statusMessage
                    failCallback(Object.assign({
                        statusCode: res.statusCode,
                        code: message,
                        message: message
                    }, resposeData === '' ? {} : JSON.parse(resposeData)))
                    return
                }
                if (callback) {
                    callback(resposeData === '' ? {} : JSON.parse(resposeData))
                }
                //console.log('response content: ', data, res.statusCode)
            })
        })

        req.on('err', (e) => {
            console.log('request error: ', e)
            if (failCallback) {
                failCallback(e)
            }
        });

        req.on('error', (e) => {
            console.log('request error: ', e)
            if (failCallback) {
                failCallback(e)
            }
        });

        if (data) {
            if (typeof data !== 'string') {
                data = JSON.stringify(data)
            }
            req.write(data)
        }
        req.end()
    }
}

export default RestClient
